package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 描述:40. 组合总和 II
 *
 * @author Madison You
 * @created 19:08
 */
public class Mid_40_CombinationSum2 {
    public static void main(String[] args) {
        new Mid_40_CombinationSum2().combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8);
    }

    List<List<Integer>> list = new ArrayList<>();

    List<Integer> temp = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        boolean[] flag = new boolean[candidates.length];
        Arrays.sort(candidates);
        back(candidates, target, 0, flag);
        return list;
    }

    private void back(int[] candidates, int target, int i , boolean[] flag) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            list.add(new ArrayList<>(temp));
            return;
        }
        for (int j = i; j < candidates.length; j++) {
            if (j > 0 && candidates[j] == candidates[j - 1] && !flag[j - 1]) {
                continue;
            }
            flag[j] = true;
            temp.add(candidates[j]);
            back(candidates, target - candidates[j], j + 1 , flag);
            flag[j] = false;
            temp.remove(temp.size() - 1);
        }
    }
}
